package com.jnchen.jwt.util;

import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.pkcs.RSAPrivateKeyStructure;
import org.bouncycastle.asn1.x509.RSAPublicKeyStructure;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemWriter;

import java.io.IOException;
import java.io.StringWriter;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;

/**
 * RSA密钥工具类
 *
 * @author jnchen
 * @date 2020/10/30 11:48
 */
public class RsaUtil {


    public static KeyPair getRsaKey() {
        KeyPairGenerator keyPairGenerator = null;
        try {
            keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        assert keyPairGenerator != null;
        keyPairGenerator.initialize(2048);
        return keyPairGenerator.generateKeyPair();
    }

    public static String[] getPemRsaKey() throws IOException {
        KeyPair keyPair = getRsaKey();

        // PKCS8 -> PKCS1
        byte[] priBytes = keyPair.getPrivate().getEncoded();
        PrivateKeyInfo pki = PrivateKeyInfo.getInstance(priBytes);
        RSAPrivateKeyStructure pkcs1Key = RSAPrivateKeyStructure.getInstance(pki.getPrivateKey());

        PemObject pemObject = new PemObject("RSA PRIVATE KEY", pkcs1Key.getEncoded());
        StringWriter stringWriter = new StringWriter();
        PemWriter pemWriter = new PemWriter(stringWriter);
        pemWriter.writeObject(pemObject);
        pemWriter.close();

        String privateKey = stringWriter.toString();


        byte[] pubBytes = keyPair.getPublic().getEncoded();
        SubjectPublicKeyInfo spkInfo = SubjectPublicKeyInfo.getInstance(pubBytes);
        RSAPublicKeyStructure ans1PubKey = RSAPublicKeyStructure.getInstance(spkInfo.getPublicKey());

        PemObject pubPemObject = new PemObject("RSA PUBLIC KEY", ans1PubKey.getEncoded());
        StringWriter pubStringWriter = new StringWriter();
        PemWriter pubPemWriter = new PemWriter(pubStringWriter);
        pubPemWriter.writeObject(pubPemObject);
        pubPemWriter.close();


        String publicKey = pubStringWriter.toString();

        return new String[]{privateKey, publicKey};
    }
}